// SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
// SPDX-License-Identifier: Mulan PSL v2
package com.geniusai.aip.auth.domain.convertor;

import com.geniusai.aip.auth.config.ExternalConfig;
import com.geniusai.aip.auth.domain.UserDO;
import com.geniusai.aip.auth.domain.UserVO;
import com.geniusai.aip.auth.domain.VGpuAllocateVO;
import com.geniusai.aip.auth.exception.AuthLoginException;
import com.geniusai.aip.auth.exception.AuthLoginExceptionEnum;
import com.geniusai.aip.auth.service.MetricService;
import com.geniusai.aip.feature.common.web.Response;
import com.geniusai.aip.feature.common.web.utils.UrlUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import static com.geniusai.aip.auth.constants.AuthCommonConstants.GET_PROJECT_NUM_URL;

/**
 * @author hml14563
 * @date 2021/4/30
 */
@Slf4j
@AllArgsConstructor
public class UserVoConverter extends BaseConverter<UserDO, UserVO> {

    private ExternalConfig externalConfig;

    private MetricService metricService;

    private RestTemplate restTemplate;

    @Override
    protected void convert(UserDO from, UserVO to) {
        super.convert(from, to);

        VGpuAllocateVO vGpuAllocateVO = metricService.getUserAllocateVGpu(from.getUserId());
        Integer allocatedVolumeSize = metricService.getAllocatedStorageByUserId(from.getUserId());

        to.setProjectNum(getProjectNumByUserId(from.getUserId()));
        to.setVGpuMemory(from.getVgpuMemory());
        to.setVolumeSize(from.getVolumeSize());
        to.setCpuNum(from.getCpuNum());
        to.setMemorySize(from.getMemorySize());
        to.setAllocatedVGpuMemory(vGpuAllocateVO.getAllocatedVGpuMemory());
        to.setAllocatedMemorySize(vGpuAllocateVO.getAllocatedMemorySize());
        to.setAllocatedCpuNum(vGpuAllocateVO.getAllocatedCpuNum());
        to.setAllocatedVolumeSize(allocatedVolumeSize);


    }

    private Integer getProjectNumByUserId(String userId) {
        try {
            return (Integer) restTemplate.getForObject(
                    UrlUtils.createUrl(
                            externalConfig.getWebService(),
                            externalConfig.getWebServicePort(), GET_PROJECT_NUM_URL
                    ), Response.class, userId
            ).getData();
        } catch (Exception e) {
            throw new AuthLoginException(AuthLoginExceptionEnum.FAIL_CONNECT_WEBSERVICE, e);
        }
    }
}
